<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 消息展示区域 - 固定高度 -->
        <div class="message-container-wrapper">
          <div class="message-container" ref="messageContainer">
            <div v-for="(message, index) in messages" :key="index" class="message-item">
              <div :class="['message-bubble', message.role]">
                <div class="message-avatar">
                  <a-avatar :icon="message.role === 'user' ? 'user' : 'robot'" />
                </div>
                <div class="message-content">
                  <div class="message-role">{{ message.role === 'user' ? '您' : 'AI助手' }}</div>
                  <div class="message-text">{{ message.content }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <a-textarea
            v-model="inputMessage"
            placeholder="请输入您的问题..."
            :auto-size="{ minRows: 2, maxRows: 6 }"
            @pressEnter="handlePressEnter"
          />
          <div class="input-actions">
            <a-button
              type="primary"
              @click="handleSendMessage"
              :loading="loading"
              icon="send"
            >
              发送
            </a-button>
            <a-button
              style="margin-left: 8px"
              @click="clearConversation"
              icon="delete"
            >
              清空
            </a-button>
          </div>
        </div>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import axios from 'axios'
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import { getFileAccessHttpUrl } from '@/api/manage'
import { fileSizeLimit } from '@/api/api'

export default {
  name: "talk",
  data() {
    return {
      messages: [],
      inputMessage: '',
      loading: false,
      streamingResponse: '',
      abortController: null,
      cardStyle: {
        height: '600px',
        display: 'flex',
        flexDirection: 'column'
      }
    }
  },
  mounted() {
    this.messages.push({
      role: 'assistant',
      content: '您好！我是AI助手，请问有什么可以帮您？'
    });
  },
  methods: {
    handlePressEnter(e) {
      e.preventDefault();
      this.handleSendMessage();
    },

    async handleSendMessage() {
      if (this.loading) return;

      if (!this.inputMessage.trim()) {
        this.$message.warning('请输入消息内容');
        return;
      }

      const userMessage = this.inputMessage;
      this.messages.push({
        role: 'user',
        content: userMessage
      });

      this.inputMessage = '';
      this.loading = true;
      this.streamingResponse = '';
      this.scrollToBottom();

      // 创建新的AI消息占位
      const aiMessageIndex = this.messages.push({
        role: 'assistant',
        content: ''
      }) - 1;

      try {
        // 取消之前的请求（如果有）
        if (this.abortController) {
          this.abortController.abort();
        }

        this.abortController = new AbortController();

        const response = await fetch('/jshERP-boot/ai/mcp-stream', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)
          },
          body: JSON.stringify({ message: userMessage }),
          signal: this.abortController.signal
        });

        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

        // 手动解析SSE流
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';

        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          
          buffer += decoder.decode(value, { stream: true });
          
          // 按SSE格式解析（以\n\n分隔消息）
          const messages = buffer.split('\n\n');
          buffer = messages.pop() || ''; // 保留不完整的消息
          
          for (const msg of messages) {
            // 提取data:后的内容
            const dataLine = msg.split('\n').find(line => line.startsWith('data:'));
            if (dataLine) {
              const content = dataLine.substring(5).trim();
              this.streamingResponse += content;
              
              // 直接更新内容，不做任何格式化
              this.messages[aiMessageIndex].content = this.streamingResponse;
              this.scrollToBottom();
            }
          }
        }

        // 处理最后剩余的数据
        if (buffer) {
          const dataLine = buffer.split('\n').find(line => line.startsWith('data:'));
          if (dataLine) {
            this.streamingResponse += dataLine.substring(5).trim();
            this.messages[aiMessageIndex].content = this.streamingResponse;
          }
        }

      } catch (error) {
        if (error.name === 'AbortError') {
          console.log('请求已取消');
          return;
        }
        
        console.error('请求失败:', error);
        this.$message.error(`请求失败: ${error.message}`);
        
        if (this.messages[aiMessageIndex].content === '') {
          this.messages.splice(aiMessageIndex, 1);
        }
      } finally {
        this.loading = false;
        this.abortController = null;
        this.scrollToBottom();
      }
    },

    clearConversation() {
      // 取消当前请求
      if (this.abortController) {
        this.abortController.abort();
        this.abortController = null;
      }
      
      this.messages = [{
        role: 'assistant',
        content: '您好！我是AI助手，请问有什么可以帮您？'
      }];
      this.streamingResponse = '';
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    }
  },
  watch: {
    messages: {
      handler() {
        this.scrollToBottom();
      },
      deep: true
    },
    loading(newVal) {
      if (newVal) {
        this.scrollToBottom();
      }
    }
  },
  beforeDestroy() {
    // 组件销毁前取消请求
    if (this.abortController) {
      this.abortController.abort();
    }
  }
}
</script>

<style scoped>
/* 页面大小 */
.message-container-wrapper {
  height: 490px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-bottom: 16px;
}

.message-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #f5f5f5;
}

.message-item {
  margin-bottom: 16px;
}

.message-bubble {
  display: flex;
  max-width: 90%;
}

.message-bubble.user {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 8px;
}

.message-content {
  padding: 12px 16px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  max-width: calc(100% - 60px);
}

.message-bubble.user .message-content {
  background: #1890ff;
  color: white;
}

.message-role {
  font-size: 12px;
  color: #666;
  margin-bottom: 6px;
  font-weight: 500;
}

.message-bubble.user .message-role {
  color: rgba(255,255,255,0.8);
}

/* 最简单的消息文本样式 - 使用pre-wrap保留所有格式 */
.message-text {
  white-space: pre-wrap;
  word-break: break-word;
  overflow-wrap: anywhere;
  line-height: 1.6;
  font-size: 14px;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.message-bubble.user .message-text {
  color: white;
}

.input-area {
  padding: 16px;
  border-top: 1px solid #e8e8e8;
}

.input-actions {
  margin-top: 8px;
  text-align: right;
}

.message-container::-webkit-scrollbar {
  width: 6px;
}
.message-container::-webkit-scrollbar-thumb {
  background: #1890ff;
  border-radius: 3px;
}

/* 响应式调整 */
@media (max-width: 700px) {
  .message-bubble {
    max-width: 95%;
  }

  .message-container {
    padding: 10px;
  }
  
  .message-container-wrapper {
    height: 300px;
  }
  
  .cardStyle {
    height: 500px;
  }
  
  .message-content {
    padding: 10px 12px;
  }
  
  .message-text {
    font-size: 13px;
  }
}
</style>